package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.config.R;
import com.example.entity.Employee;
import com.example.service.LoginService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
@Slf4j
@RestController
@RequestMapping("employee")
public class LoginController {


    @Autowired
    private LoginService loginService;

    @GetMapping("{id}")
    public R findById(@PathVariable Long id){
        return loginService.findById(id);

    }

    @PostMapping("logout")
    public R logut(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }

    @PostMapping("login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        R<Employee> r = loginService.login(employee);
        if (r.getCode()==1){
            session.setAttribute("employee",r.getData().getId());
        }
        return r;
    }



  @RequestMapping("/page")
    public R page(Integer page,Integer pageSize,String name){
        IPage<Employee> pageInfo=new Page<>(page,pageSize);
      LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();

      if (name!=null){
          queryWrapper.like(Employee::getName, name);
      }
      //queryWrapper.orderByDesc(Employee::getUpdateTime);
      //loginService.page(pageInfo,queryWrapper);
      IPage<Employee> iPage = loginService.page(pageInfo, queryWrapper);
      return R.success(iPage);
  }
    @PostMapping
    public R addEmployee(@RequestBody Employee employee,HttpSession session){
        Long id=(Long)session.getAttribute("employee");
        employee.setCreateUser(id);
        employee.setUpdateUser(id);
        loginService.add(employee);
        return R.success("成功");
    }

    @PutMapping
    public R updateEmployee(@RequestBody Employee employee,HttpSession session){
        Long id= (Long) session.getAttribute("employee");
        employee.setUpdateUser(id);

        loginService.updateEmp(employee);
        return R.success("修改成功");
    }


}
